<template>
  <div class="property-panel" ref="propertyPanel">
    <el-form :inline="true" :model="form" label-width="90px" size="small">
      <el-collapse v-model="activeNames">
        <el-collapse-item name="normal">
          <template slot="title">
            <i class="iconfont icon-shezhi itemHeadText"></i>&nbsp;&nbsp;基础设置
          </template>
          <el-form-item label="节点编号">
            <el-input v-model="form.id" @change="(value) => updateProperties({id: value})"></el-input>
          </el-form-item>
          <el-form-item label="节点名称" v-if="notProcess">
            <el-input v-model="form.name" @input="nameChange"></el-input>
          </el-form-item>
          <!-- 分支允许添加条件 -->
          <el-form-item label="分支条件" v-if="sequenceFlow">
            <el-input v-model="form.conditionExpression.body"></el-input>
          </el-form-item>

          <el-form-item label="信号量" v-if="signalEvent">
            <el-input v-model="signalRef"
                      style="width: 230px"
                      placeholder="请选择"
                      :readonly="true"
                      clearable>
              <template slot="append">
                <i class="el-icon-document auditIcon" @click="expressTableShow('signalRef', signalRef)"></i>
              </template>
            </el-input>
          </el-form-item>

        </el-collapse-item>
        <!--  处理人      -->
        <el-collapse-item name="audit" v-if="userTask">
          <template slot="title">
            <i class="el-icon-user itemHeadText"></i>&nbsp;&nbsp;处理人
          </template>
          <el-form-item label="指定人员">
            <el-input v-model="form.assigneeLabels"
                      style="width: 230px"
                      placeholder="请选择"
                      :readonly="true"
                      clearable>
              <template slot="append">
                <i class="el-icon-user auditIcon" @click="userTableShow('assignee', form.assignee)"></i>
                <i class="el-icon-document auditIcon" @click="expressTableShow('assignee', form.assignee)"></i>
                <i class="el-icon-remove auditIcon" @click="updateProperties({assignee: null, label: ''})"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="指定部门">
            <el-input v-model="form.deptLabels"
                      style="width: 230px"
                      placeholder="请选择"
                      :readonly="true"
                      clearable>
              <template slot="append">
                <i class="el-icon-user auditIcon" @click="deptTableShow('dept', form.dept)"></i>
                <i class="el-icon-remove auditIcon" @click="updateProperties({dept: null})"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="候选角色">
            <el-input
              style="width: 230px"
              v-model="form.candidateGroupLabels"
              placeholder="请选择"
              :readonly="true"
              clearable>
              <template slot="append">
                <i class="el-icon-user auditIcon"
                   @click="userTableShow('candidateGroups',form.candidateGroups)"></i>
                <i class="el-icon-remove auditIcon" @click="updateProperties({candidateGroups: null, label: ''})"></i>
              </template>
            </el-input>
          </el-form-item>
          <div style='width: 100%;text-align: center'>
            <span style='letter-spacing: 1.5px'>候选部门(用于不同建设单位下相同的部门过滤)</span>
          </div>
          <el-form-item label="候选部门" >
            <el-input v-model="form.deptRoleLabels"
                      style="width: 230px"
                      placeholder="请选择"
                      :readonly="true"
                      clearable>
              <template slot="append">
                <i class="el-icon-user auditIcon" @click="deptRoleTableShow('deptRole', form.deptRole)"></i>
                <i class="el-icon-remove auditIcon" @click="updateProperties({deptRole: null})"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="指定过滤器">
            <el-select v-model="form.filtersList"
                       placeholder="请选择" @change="changeFilter" clearable multiple>
              <el-option
                v-for="item in filterList"
                :key="item.code"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-checkbox v-model="description" @change="checkDesc" style="margin-left: 22px;">显示审批意见框</el-checkbox>
          <el-checkbox v-model="dueAuto" @change="checkDueAuto" style="margin-left: 22px;">显示处理人下拉框</el-checkbox>
        </el-collapse-item>

        <!--  会签配置      -->
        <el-collapse-item name="sign" v-if="multi">
          <template slot="title">
            <i class="iconfont icon-peoples itemHeadText"></i>&nbsp;&nbsp;会签配置
          </template>
          <el-form-item label="循环集合">
            <el-input v-model="form.loopCharacteristics.collection" placeholder="例:${selectedUsers}"
                      clearable></el-input>
          </el-form-item>
          <el-form-item label="元素变量">
            <el-input v-model="form.loopCharacteristics.elementVariable"
                      @input="variableChange"
                      placeholder="请输入元素变量（不可重复）"
                      clearable></el-input>
          </el-form-item>
          <el-form-item label="完成条件">
            <el-select v-model="form.loopCharacteristics.completionCondition.body" @change="changeCondition"
                       placeholder="请选择">
              <el-option
                v-for="item in completeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-collapse-item>

        <el-collapse-item name="buttonManage" v-show="userTask">
          <template slot="title">
            <i class="iconfont icon-erji itemHeadText"></i>&nbsp;&nbsp;按钮管理
          </template>
          <el-button class="el-icon-plus add" type="primary" size="mini" style="float: right"
                     @click="addButtonDialogShow"></el-button>
          <el-button class="el-icon-refresh-left" type="primary" size="mini" style="float: right;"
                     @click="initButton"></el-button>
          <el-table :data="view.buttonTableData" ref="buttonTable"
                    @select="handleSelectionChangeBtn"
          >
            <el-table-column type="selection" width="30"/>
            <el-table-column prop="buttonName" label="按钮名称" :show-overflow-tooltip="true"/>
            <el-table-column prop="expression" label="表达式" :show-overflow-tooltip="true"/>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" class="el-icon-edit-outline"
                           @click="handleClickDeal('edit',scope.$index, scope.row, 'button')"></el-button>
                <el-button size="mini" type="danger" class="el-icon-delete"
                           @click="handleClickDeal('delete',scope.$index, scope.row, 'button')"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>

        <!--   表单     -->
        <el-collapse-item name="form" v-show="formData">
          <template slot="title">
            <i class="el-icon-document-copy itemHeadText"></i>&nbsp;&nbsp;表单
          </template>
          <el-table
            ref="formTable"
            :data="view.formData"
            @select="handleSelectionChange"
            @select-all="selectAll"
            style="width: 100%;padding: 10px">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column prop="name" label="字段描述" :show-overflow-tooltip="true"/>
            <el-table-column prop="value" label="字段编码" :show-overflow-tooltip="true"/>
          </el-table>
        </el-collapse-item>

        <!--  执行监听      -->
        <el-collapse-item name="performListener">
          <template slot="title">
            <i class="iconfont icon-laba itemHeadText"></i>&nbsp;&nbsp;执行监听
          </template>
          <el-button class="el-icon-plus add" type="primary" size="mini" style="float: right"
                     @click="performOrTaskShow('perform')"></el-button>
          <el-table :data="view.listenerData" style="width: 100%;padding: 10px">
            <el-table-column prop="event" label="事件" :show-overflow-tooltip="true"/>
            <el-table-column label="值" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{scope.row.class || scope.row.expression || scope.row.delegateExpression}}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" class="el-icon-delete"
                           @click="handleClickDeal('delete',scope.$index, scope.row, 'perform')"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>

        <el-collapse-item name="taskListener" v-show="userTask">
          <template slot="title">
            <i class="iconfont icon-erji itemHeadText"></i>&nbsp;&nbsp;任务监听
          </template>
          <el-button class="el-icon-plus add" type="primary" size="mini" style="float: right"
                     @click="performOrTaskShow('task')"></el-button>
          <el-table :data="view.taskListenerData" style="width: 100%;padding: 10px">
            <el-table-column prop="event" label="监听器" :show-overflow-tooltip="true"/>
            <el-table-column label="值" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{scope.row.class || scope.row.expression || scope.row.delegateExpression}}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" class="el-icon-delete"
                           @click="handleClickDeal('delete',scope.$index, scope.row, 'task')"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-form>

    <user-detail :postDetail="postDetailData" @updateProperties="updateProperties"></user-detail>
    <dept-detail :postDetail="postDeptDetailData" @updateProperties="updateDeptProperties"></dept-detail>
    <deptRole-detail :postDetail="postDeptRoleDetailData" @updateProperties="updateDeptRoleProperties"></deptRole-detail>
    <filter-detail :postDetail="postFilterDetailData" @updateProperties="updateDeptRoleProperties"></filter-detail>
    <expression-detail :postDetail="postExpDetailData" @updateExpression="updateExpression"
                       @delete="deleteSign"></expression-detail>
    <listener-detail :postDetail="postPerformDetailData" @updatePerformTable="updateTable"></listener-detail>
    <task-listener-detail :postDetail="postTaskDetailData" @updateTaskTable="updateTable"></task-listener-detail>
    <button-detail :postDetail="postButtonDetailData" @updateButtonTable="updateButtonTable"></button-detail>
  </div>
</template>

<script>
  import {allList as roleList} from '@/api/system/role'
  import {formField} from '@/api/wf/field'
  import {allList as userList} from '@/api/system/user'
  import button from '@/api/wf/button'
  import msgUtil from '@/utils/msgUtil'
  import helper from './helper'
  import dict from '@/api/system/dict'

  export default {
    name: "PropertyPanel",
    components: {
      userDetail: () => import('./UserDetail'),
      deptDetail: () => import('./DeptDetail'),
      expressionDetail: () => import('./expressionDetail'),
      listenerDetail: () => import('./listenerDetail'),
      taskListenerDetail: () => import('./taskListenerDetail'),
      buttonDetail: () => import('./buttonDetail'),
      filterDetail: () => import('./FilterDetail'),
      deptRoleDetail: () => import('./DeptRoleDetail.vue'),
    },
    props: {
      modeler: {
        type: Object,
        required: true
      },
      procDefKey: {
        type: String,
        default: null
      }
    },
    computed: {
      sequenceFlow() {
        if (!this.element) {
          return;
        }
        return this.element.type === "bpmn:SequenceFlow";
      },
      signalEvent() {
        if (!this.element) {
          return;
        }
        return this.element.type === "bpmn:IntermediateThrowEvent" ||
          this.element.type === "bpmn:IntermediateCatchEvent";
      },
      multi() {
        return this.isMulti() || this.reload
      },
      formData() {
        return this.userTask && this.view.formData.length > 0
      }
    },
    watch: {
      'form.showDescription': {
        handler(val) {
          this.description = val == '1'
        }
      },
      'form.dueAuto': {
        handler(val) {
          this.dueAuto = val == '1'
        }
      }
    },
    data() {
      return {
        userTask: false,
        description: false,
        dueAuto: false,
        signalRef: '',
        bpmnSignal: null,
        form: {
          id: '',
          name: '',
          dueAuto: '0',
          showDescription: false,
          candidateUsers: '',
          candidateUserLabels: '',
          candidateGroups: '',
          candidateGroupLabels: '',
          assignee: '',
          assigneeLabels: '',
          dept: '',//部门
          deptLabels: '',//部门
          filters: '',//部门
          filtersLabels: '',//部门
          filtersList: [],//部门
          deptRole: '',//部门
          deptRoleLabels: '',//部门
          conditionExpression: {
            body: ''
          },
          loopCharacteristics: {
            collection: '${selectedUsers}',
            elementVariable: '',
            completionCondition: {
              body: ''
            },
          },
          eventDefinitions: [],
          btns: null
        },
        filterList: [],
        reload: false,
        modeling: null,
        bpmnFactory: null,
        expressionData: {
          procDefKey: '',
          taskDefKey: ''
        },
        buttonData: {
          procDefKey: '',
          taskDefKey: ''
        },
        view: {
          listenerData: [],
          taskListenerData: [],
          formData: [],
          selection: [],
          buttonTableData: [],
          buttonBasicTableData: [
            {buttonName: 'report', description: '上报', type: 'primary', event: 'apply'},
            {buttonName: 'audit', description: '审批', type: 'primary', event: 'approve'},
            {buttonName: 'back', description: '回退', type: 'primary', event: 'approve', params: '{"isReject": "1"}'},
          ]
        },
        nodeType: {
          executionListener: 'activiti:ExecutionListener',
          taskListener: 'activiti:TaskListener',
          formProperty: 'activiti:FormProperty',
          signal: 'bpmn:Signal',
          signalEventDefinition: 'bpmn:SignalEventDefinition',
          formalExpression: 'bpmn:FormalExpression'
        },
        activeNames: ['normal'],
        listenerDialogShow: false,
        notProcess: true,
        postDetailData: {
          show: false,
          params: {}
        },
        postDeptDetailData: {
          show: false,
          params: {}
        },
        postDeptRoleDetailData: {
          show: false,
          params: {}
        },
        postFilterDetailData: {
          show: false,
          params: {}
        },
        postExpDetailData: {
          show: false,
          type: '0',
          params: {}
        },
        postPerformDetailData: {
          show: false,
          params: {}
        },
        postTaskDetailData: {
          show: false,
          params: {}
        },
        postFormDetailData: {
          show: false,
          params: {}
        },
        postButtonDetailData: {
          show: false,
          params: {}
        },
        rootElement: null,
        element: {},
        roles: [],
        users: [],
        completeList: [{
          label: '一个即可',
          value: '${nrOfCompletedInstances/nrOfInstances > 0 || isReject=="1"}'
        }, {
          label: '半数通过',
          value: '${nrOfCompletedInstances/nrOfInstances >= 1/2 || isReject=="1"}'
        }, {
          label: '全部通过',
          value: '${nrOfCompletedInstances/nrOfInstances >= 1 || isReject=="1"}'
        }],
      };
    },
    mounted() {
      this.init()
      this.modeling = this.modeler.get("modeling");
      this.bpmnFactory = this.modeler.get('bpmnFactory');
      this.getWfFilter()
    },
    methods: {
      init() {
        this.expressionData.procDefKey = this.procDefKey
        this.buttonData.procDefKey = this.procDefKey
        this.handleModeler()
        this.initRole()
        this.initUser()
      },
      getWfFilter() {
        dict.getByCode('wffilter').then(res => {
          this.filterList = res.data
        })
      },

      //执行监听新增保存到表格
      updateTable(param, type) {
        this.$nextTick(() => {
          const properties = {
            event: param.event
          }
          if (param.class) {
            properties.class = param.class
          }
          if (param.expression) {
            properties.expression = param.expression
          }
          if (param.delegateExpression) {
            properties.delegateExpression = param.delegateExpression
          }

          if (type == 1) {
            this.createExtensionElements(this.nodeType.executionListener, properties)
            this.view.listenerData.push(properties)
          } else {
            this.createExtensionElements(this.nodeType.taskListener, properties)
            this.view.taskListenerData.push(properties)
          }
        })
      },
      // 处理人用户选择
      userTableShow(type, value) {
        this.postDetailData = {
          show: true,
          procDefKey: this.procDefKey,
          type: type,
          params: value
        }
      },
      // 部门选择
      deptTableShow(type, value) {
        this.postDeptDetailData = {
          show: true,
          procDefKey: this.procDefKey,
          type: type,
          params: value
        }
      },
      // 部门选择
      deptRoleTableShow(type, value) {
        this.postDeptRoleDetailData = {
          show: true,
          procDefKey: this.procDefKey,
          type: type,
          params: value
        }
      },
      expressTableShow(type, value) {
        this.postExpDetailData = {
          show: true,
          type: type,
          param: this.expressionData
        }
        this.postExpDetailData.param[type] = value
      },
      // 按钮新增
      addButtonDialogShow() {
        this.postButtonDetailData = {
          show: true,
          type: 'add',
          param: this.buttonData
        }
      },
      // 新增按钮保存表格
      updateButtonTable(param, type) {
        this.buttonListPage()
      },
      // 监听器点击添加展示内容
      performOrTaskShow(value) {
        if (value === 'perform') {
          this.postPerformDetailData = {
            show: true
          }
        } else {
          this.postTaskDetailData = {
            show: true
          }
        }
      },
      handleModeler() {
        const that = this
        // 监听节点选择变化
        this.modeler.on("selection.changed", e => {
          const element = e.newSelection[0];
          this.userTask = this.isUserTask(element)
          this.element = element;
          if (!element) {
            this.notProcess = false
            return this.processNode()
          }
          this.pushActiveNames()
          this.notProcess = true

          this.form = {
            ...element.businessObject,
            ...element.businessObject.$attrs
          };
          if(this.form.filters){
            this.form.filtersList = this.form.filters.split(",")
          }
          if (this.sequenceFlow && !this.form.conditionExpression) {
            const conditionExpression = this.bpmnFactory.create(this.nodeType.formalExpression, {body: ''})
            this.updateProperties({conditionExpression: conditionExpression})
            this.form.conditionExpression = conditionExpression
          }
          // 会签设置body
          if (that.multi && !this.form.loopCharacteristics.completionCondition) {
            let completionCondition = this.bpmnFactory.create(this.nodeType.formalExpression, {body: ''})
            this.form.loopCharacteristics.completionCondition = completionCondition
            if (!this.form.loopCharacteristics.collection) {
              this.form.loopCharacteristics.collection = '${selectedUsers}'
            }
            if (!this.form.loopCharacteristics.elementVariable) {
              const variable = `var${this.element.id}`
              this.form.loopCharacteristics.elementVariable = variable
              this.variableChange(variable)
            }
          }

          const ext = this.form.extensionElements
          if (ext) {
            const values = ext.get('values')
            this.view.listenerData = values.filter(it => it.$type == this.nodeType.executionListener)
            this.view.taskListenerData = values.filter(it => it.$type == this.nodeType.taskListener)
            this.doSelectForm(values)
          } else {
            this.doSelectForm([])
          }

          if (this.userTask) {
            this.expressionData.taskDefKey = element.id
            this.buttonData.taskDefKey = element.id

            if (this.form.assignee) {
              this.form.assigneeLabels = this.filterLabels(this.form.assignee.split(','), this.users) || this.form.assignee
            }
            if (this.form.candidateUsers) {
              this.form.candidateUserLabels = this.filterLabels(this.form.candidateUsers.split(','), this.users) || this.form.candidateUsers
            }
            if (this.form.candidateGroups) {
              this.form.candidateGroupLabels = this.filterLabels(this.form.candidateGroups.split(','), this.roles) || this.form.candidateGroups
            }
            if (this.view.buttonBasicTableData) {
              this.view.buttonBasicTableData.forEach(item => {
                item.taskDefKey = element.id
                item.procDefKey = this.procDefKey
              })
            }
            const selectBtn = this.form.btns || ''
            this.doSelectBtns(selectBtn.split(','))
          }

          if (this.signalEvent && this.form.eventDefinitions) {
            if (this.form.eventDefinitions[0].signalRef) {
              this.signalRef = this.form.eventDefinitions[0].signalRef.id
            } else {
              this.signalRef = ''
            }
          }

        });

        //  监听节点属性变化
        this.modeler.on("element.changed", e => {
          const {element} = e;
          if (!element) return;
          //  新增节点需要更新回属性面板
          if (element.id === this.form.id) {
            this.form.name = element.businessObject.name;
            this.form = {...this.form};
          }
        });
      },
      isUserTask(element) {
        if (element && element.type == 'bpmn:UserTask') {
          return true
        } else {
          return false
        }
      },
      pushActiveNames() {
        let items = ['normal']
        if (this.userTask) {
          items = ['normal', 'sign', 'audit', 'buttonManage']
        }
        this.activeNames = items
      },
      // 属性面板名称，更新回流程节点
      nameChange(name) {
        this.modeling.updateLabel(this.element, name);
      },
      variableChange(value) {
        const assignee = '${' + value + '}'
        if (this.userTask) {
          this.updateProperties({assignee: assignee, label: assignee})
        }
      },
      // 更新属性
      updateProperties(properties) {
        if (properties.hasOwnProperty('assignee')) {
          this.form.assignee = properties.assignee
          this.form.assigneeLabels = properties.label
          // label不保存到xml
          delete properties.label
        } else if (properties.hasOwnProperty('candidateUsers')) {
          this.form.candidateUsers = properties.candidateUsers
          this.form.candidateUserLabels = properties.label
          delete properties.label
        } else if (properties.hasOwnProperty('candidateGroups')) {
          this.form.candidateGroups = properties.candidateGroups
          this.form.candidateGroupLabels = properties.label
          delete properties.label
        }else if (properties.hasOwnProperty('deptRole')) {
          this.form.deptRole = properties.deptRole
          delete properties.label
        }
        console.log(this.element)
        this.modeling.updateProperties(this.element, properties);
      },

      // 更新部门属性
      updateDeptProperties(properties) {
          this.form.dept = properties.dept
          this.form.deptLabels = properties.label
          // label不保存到xml
          delete properties.label
        properties.deptLabels = this.form.deptLabels
        this.modeling.updateProperties(this.element, properties);
      },
      // 更新部门角色属性
      updateDeptRoleProperties(properties) {
        this.form.deptRole = properties.deptRole
        this.form.deptRoleLabels = properties.label
        // label不保存到xml
        delete properties.label
        this.updateProperties({deptRole:this.form.deptRole, deptRoleLabels:this.form.deptRoleLabels} )
      },
      updateExpression(expression) {
        if (expression.assignee) {
          this.form.assignee = expression.assignee
          this.form.assigneeLabels = expression.assignee
        } else if (expression.candidateUsers) {
          this.form.candidateUsers = expression.candidateUsers
          this.form.candidateUserLabels = expression.candidateUsers
        } else if (expression.candidateGroups) {
          this.form.candidateGroups = expression.candidateGroups
          this.form.candidateGroupLabels = expression.candidateGroups
        } else if (expression.signalRef) {
          this.signalRef = expression.signalRef
          this.updateSign()
          return
        }
        this.modeling.updateProperties(this.element, expression);
      },
      updateSignDefinitions() {
        const that = this
        return new Promise((resolve, reject) => {
          try {
            const roots = this.modeler._definitions.rootElements
            const el = helper.filterSign(roots, that.signalRef)
            if (!el) {
              const signal = this.bpmnFactory.create(this.nodeType.signal, {id: that.signalRef, name: that.signalRef})
              roots.push(signal)
              resolve(signal)
            } else {
              el.name = that.signalRef
              resolve(el)
            }
          } catch (e) {
            reject(e)
          }
        })
      },
      deleteSign(form) {
        const roots = this.modeler._definitions.rootElements
        helper.deleteSign(roots, form.signalRef)
      },
      updateSign() {
        // 没有就删除， 有就加一个
        this.updateSignDefinitions().then(res => {
          const eventDefinitions = this.form.eventDefinitions
          eventDefinitions[0].signalRef = res
          this.updateProperties({eventDefinitions: eventDefinitions})
        })
      },
      createExtensionElements(type, properties) {
        const moddle = this.modeler.get('moddle')
        const element = moddle.create(type, properties);
        let extensionElements = this.form.extensionElements;
        if (!extensionElements) {
          extensionElements = moddle.create('bpmn:ExtensionElements')
          this.updateProperties({extensionElements: extensionElements})
        }
        extensionElements.get('values').push(element);
      },
      deleteExtensionElements(type, properties) {
        const extensionElements = this.form.extensionElements
        properties.$type = type
        if (extensionElements) {
          const arr = extensionElements.get('values')
          let index = arr.findIndex(it => {
            let eq = true
            for (const p in it) {
              if (it[p] && typeof it[p] == 'object') {
                const sub = it[p]
                for (const p1 in sub) {
                  if (sub[p1] && typeof it[p] != 'function' && sub[p1] !== properties[p][p1]) {
                    eq = false
                    break
                  }
                }
              }
              if (!eq) {
                break
              }

              if (it[p] && typeof it[p] != 'function' && it[p] !== properties[p]) {
                eq = false
                break
              }
            }
            return eq
          })
          index >= 0 && arr.splice(index, 1)
          this.updateProperties({extensionElements: extensionElements})
        }
      },
      processNode() {
        if (!this.modeler._definitions.rootElements) {
          return
        }
        const element = this.modeler._definitions.rootElements[0]
        this.form.id = element.id
        this.form.type = element.$type
        this.form.name = ''
        this.element = element
        if (!this.rootElement) {
          this.rootElement = element
          this.initForm()
        }
      },
      handleClickDeal(type, index, row, tableType) {
        switch (type) {
          // 取消，关闭窗口
          case 'cancel':
            this.listenerDialogShow = false
            break
          // 保存
          case 'submit':
            this.listenerDialogShow = false
            break
          // 编辑
          case 'edit':
            this.postButtonDetailData = {
              show: true,
              param: row,
              type: type
            }
            break
          // 删除
          case 'delete':
            this.$confirm('你确定删除选中的数据吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let param
              if (tableType === 'perform') {
                param = this.view.listenerData[index]
                this.view.listenerData.splice(index, 1)
              } else if (tableType === 'button') {
                this.buttonDelete(row)
              } else {
                param = this.view.taskListenerData[index]
                this.view.taskListenerData.splice(index, 1)
              }
              this.deleteExtensionElements(this.nodeType.executionListener, param)
            }).catch(() => {
            })
            break
        }
      },
      initRole() {
        roleList().then(res => {
          let arr = []
          res.data.forEach(o => {
            arr.push({
              label: o.name,
              value: o.id
            })
          })
          return arr;
        }).then(res => {
          this.roles = res
        });
      },
      initUser() {
        userList(this.search).then(res => {
          this.users = res.data
        })
      },
      initForm() {
        const formKey = this.rootElement.id
        formField(formKey).then(res => {
          this.view.formData = res.data || []
        }).catch(() => {
        })
      },
      doSelectForm(values) {
        const that = this
        if (!this.formData || !this.userTask) {
          return
        }
        const selection = []
        for (let i = values.length - 1; i >= 0; i--) {
          const selected = values[i]
          if (selected.$type != this.nodeType.formProperty) {
            continue
          }
          let exists = false
          this.view.formData.forEach(it => {
            if (it.value == selected.id) {
              this.$nextTick(() => {
                selection.push(it)
              })
              exists = true
            }
          })
          if (!exists) {
            values.splice(i, 1);
          }
        }
        this.view.selection = selection
        this.$nextTick(() => {
          if (that.$refs.formTable) {
            that.$refs.formTable.clearSelection()
            selection.forEach(it => {
              that.$refs.formTable.toggleRowSelection(it)
            })
          }
        })
      },
      handleSelectionChange(selection, row) {
        const index = this.view.selection.findIndex(it => it.value == row.value)
        if (index >= 0) {
          this.deleteExtensionElements(this.nodeType.formProperty, {id: row.value})
          this.view.selection.splice(index, 1)
        } else {
          this.createExtensionElements(this.nodeType.formProperty, {id: row.value})
          this.view.selection.push(row)
        }
      },
      doSelectBtns(values) {
        const that = this
        const selection = []
        this.buttonListPage().then((res) => {
          values.forEach(value => {
            const index = res.findIndex(it => it.buttonName == value)
            if (index >= 0) {
              selection.push(res[index])
            }
          })
          if (!that.$refs.buttonTable) {
            return
          }
          this.$nextTick(() => {
            that.$refs.buttonTable.clearSelection()
            selection.forEach(it => {
              that.$refs.buttonTable.toggleRowSelection(it)
            })
          })
        })
      },
      handleSelectionChangeBtn(selection, row) {
        let values = []
        selection.forEach(it => {
          values.push(it.buttonName)
        })
        let value = values.length > 0 ? values.join(',') : ''
        this.updateProperties({btns: value})
      },
      selectAll(selection) {
        if (selection.length == 0) {
          this.view.selection.forEach(row => {
            this.deleteExtensionElements(this.nodeType.formProperty, {id: row.value})
          })
        } else {
          selection.forEach(row => {
            const index = this.view.selection.findIndex(it => it.value == row.value)
            if (index == -1) {
              this.createExtensionElements(this.nodeType.formProperty, {id: row.value})
            }
          })

          this.view.selection = selection.slice(0)
        }
      },
      filterLabels(one, two) {
        if (one && two) {
          let list = []
          one.forEach(item => {
            let obj = two.find(data => {
              return data.value == item || data.id == item
            })
            if (obj) {
              if (obj.value) {
                list.push(obj.label)
              }
              if (obj.id) {
                list.push(obj.name)
              }
            }
          })
          return list.join(',');
        }
      },
      buttonListPage(flag) {
        this.buttonData.pageSize = 9999
        return button.listPage(this.buttonData).then(response => {
          this.view.buttonTableData = response.data.content
          return response.data.content
        })
      },
      // 删除
      async buttonDelete(row) {
        const ids = []
        ids.push(row.id)
        await button.del(ids)
        msgUtil.success2('删除成功!')
        this.buttonListPage(true)
      },
      initButton() {
        this.view.buttonBasicTableData.forEach(item => {
          button.add(item).then(response => {
            this.buttonListPage()
          })
        })
      },
      isMulti() {
        if (!this.element) {
          return;
        }
        if (!this.element.businessObject || !this.element.businessObject.loopCharacteristics) {
          return false
        }
        const type = this.element.businessObject.loopCharacteristics.$type
        if (!type) {
          return false
        }
        return type === 'bpmn:MultiInstanceLoopCharacteristics'
      },
      changeCondition(value) {
        let loopCharacteristics = this.form.loopCharacteristics;
        loopCharacteristics.completionCondition.body = value
        this.updateProperties({loopCharacteristics: loopCharacteristics})
      },
      changeFilter(value) {
        let filters = this.form.filtersList.join(",");
        filters = value
        this.updateProperties({filters: filters})
      },
      checkDesc(value) {
        const desc = value ? '1' : '0'
        this.updateProperties({showDescription: desc})
      },
      checkDueAuto(value) {
        const dueAuto = value ? '1' : '0'
        this.updateProperties({dueAuto: dueAuto})
      }
    },
  };
</script>

<style lang="scss" scoped>
  .property-panel {
    position: absolute;
    right: 0px;
    top: 0px;
    border-left: 1px solid #cccccc;
    //padding: 20px 0;
    width: 350px !important;
    height: 100%;
    overflow: auto;
    background-color: #fafafa;
  }

  .itemHeadText {
    margin-left: 42px !important;
  }

  .auditIcon {
    cursor: pointer;
    padding: 4px;
  }

  .add {
    margin: 2px 0 10px 14px;
  }

  ::v-deep {
    .el-collapse-item__header {
      position: relative;
      font-size: 14px;
      font-weight: bold;
      background-color: #fafafa;
      color: rgba(0, 0, 0, .85)
    }
    .el-collapse-item__arrow {
      position: absolute;
      left: 0;
      top: 37%;
      //margin-bottom: 7px;
      //transform: translateY(-50%);
      width: 14px;
      height: 14px;
      font-size: 14px;
      font-weight: bold;
      margin-left: 14px;
    }
    .el-input-group__append {
      padding: 0;
    }
    .el-collapse-item__content {
      padding-top: 15px;
    }

    .el-table__body-wrapper {
      overflow-x: hidden;
    }
  }
</style>